<template>
  <div class="department-container">
    <div class="app-container">
      <el-card class="box-card department-box">
        <!-- 头部 -->
        <DeptOptions :row="company" :is-root="true" @click-add="onClickAdd" />

        <!-- 树形 -->
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <!-- 使用插槽的时候，希望拿到组件内部的数据 -->
          <template v-slot="scope">
            <DeptOptions :row="scope.data" @click-edit="onClickEdit" @ondel="loadDepartments" @click-add="onClickAdd" />
          </template>
        </el-tree>
      </el-card>
    </div>

    <!-- 添加部门弹窗组件 -->
    <DeptAdd ref="addDept" :row="deptRow" :show-dialog.sync="dialogVisible" @add-success="loadDepartments" />
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments.js'
import { transListToTree } from '@/utils'
import DeptOptions from './components/dept-options.vue'
import DeptAdd from './components/dept-add.vue'
export default {
  name: 'Departments',
  components: {
    DeptOptions,
    DeptAdd
  },
  data() {
    return {
      defaultProps: {
        label: 'name' // 显示数据里的name
      },
      company: {}, // 记录公司信息
      depts: [], // 树形信息
      dialogVisible: false, //
      deptRow: {}

    }
  },

  created() {
    this.loadDepartments()
  },

  methods: {
    // 获取数据
    async loadDepartments() {
      const res = await getDepartments()
      this.company = { name: res.companyName, manager: '负责人', children: transListToTree(res.depts, '') }
      // 用递归函数处理返回的数据
      this.depts = transListToTree(res.depts, '')
    },

    // 子组件点击添加部门触发
    onClickAdd(val) {
      this.dialogVisible = true
      this.deptRow = val
    },

    // 子组件点击查看触发
    onClickEdit(val) {
      this.dialogVisible = true
      this.deptRow = val
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.department-container {

  .el-tree {
    margin-top: 10px;
    padding-top: 10px;
    border-top: 1px solid #ccc;
  }
}
</style>
